<template>
  <pageTabelLayout>
    <template #pageHeader>
      <div class="search-form isheader" v-if="headerShow">
        <div>
          <a-form size="small" :model="pageData" layout="inline">
            <a-form-item label="供应商名称" v-if="permissionStore.hasPermisson('gyszl.cx')">
              <!-- <a-select popup-container="html"  class="bacClass" :style="{ width: '200px' }" :loading="loading" @search="handleSearch"
                            v-model="pageData.dropDownData" :filter-option="false" allow-search allow-clear
                            @focus="focusSel">
                            <a-option v-for="item in pageData.nameList" :value="item.providerName">{{item.providerName}}
                            </a-option>
                        </a-select> -->
              <a-input allow-clear class="bacClass" placeholder="" v-model="pageData.dropDownData"
                       @press-enter="huiche"/>
            </a-form-item>
          </a-form>
        </div>
        <div>
          <Toolbar :items="[...pageData.btnList, '导入']" @add="addHandler" @del="deleteHandler" @select="selectHandler"
                   @export="exports" @import="importHandler" @excel="downloadHandler">
          </Toolbar>
        </div>
      </div>
      <div class="my-divisders">
        <a-divider orientation="center">
          <icon-double-up v-if="headerShow" @click="headerShow = false" :strokeWidth="2" :size="18"/>
          <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18"/>
        </a-divider>
      </div>
      <div class="my-tool-bar">
        <!-- , '导出', '导入' -->
        <!-- <Toolbar :items="['查询', '新增', '删除']" @add="addHandler" @del="deleteHandler" @select="selectHandler"
                    @export="exports" @import="importHandler" @excel="downloadHandler">
                </Toolbar> -->
      </div>
    </template>
    <template #pageTabel>
      <a-spin :loading="pageData.pageLoading" tip="加载中" dot style="height: 100%; width: 100%; z-index: 999">
        <div style="width: 100%; height: 100%">
          <encapsulation-agrid ref="table1Ref" :configaggrid="configTable1"
          ></encapsulation-agrid>
        </div>
      </a-spin>
    </template>
    <a-drawer style="z-index: 999" ok-text="保存" cancel-text="关闭" :style="{ zIndex: 9999 }" :mask-closable="false"
              height="100%" popup-container=".table-page-body" placement="bottom" :visible="pageData.showAdd"
              unmountOnClose
              @ok="sideOk" @cancel="pageData.showAdd = false" :ok-loading="pageData.pageLoading">
      <template #title>
        {{ pageData.sideTitle }}
      </template>

      <div style="width: 1540px; overflow: auto" class="scrollbar">
        <el-scrollbar>
          <a-form ref="formRef" layout="inline" :model="dataForm" :label-col-props="{ span: 10 }"
                  :wrapper-col-props="{ span: 14 }" size="mini">
            <a-form-item :style="{ width: '355px' }" label="供应商编号" field="providerCode"
                         :rules="[{ validator: isChiese }, { required: true, message: '编号必填' }]"
                         :validate-trigger="['change', 'blur']" label-col-flex="120px">
              <a-input placeholder="" :style="{ width: '300px' }" v-model="dataForm.providerCode" @blur="inputBlur"
                       disabled/>
            </a-form-item>
            <a-form-item :style="{ width: '355px' }" label="供应商分类" field="providerType"
                         :rules="[{ required: true, message: '供应商分类必填' }]" :validate-trigger="['change', 'blur']"
                         label-col-flex="120px">
              <a-select popup-container="html" :style="{ width: '300px' }" class="bacClass"
                        v-model="dataForm.providerType" @change="provideTypeChange" allow-clear>
                <a-option v-for="item in pageData.providerTypeList">{{ item.detailName }}</a-option>
              </a-select>
            </a-form-item>
            <a-form-item :style="{ width: '355px' }" label="供应商名称" field="providerName"
                         :rules="[{ required: true, message: '名称必填' }]" :validate-trigger="['change', 'blur']"
                         label-col-flex="120px">
              <a-input placeholder="" :style="{ width: '300px' }" class="bacClass" v-model="dataForm.providerName"/>
            </a-form-item>

            <a-form-item :style="{ width: '355px' }" label="供应商类别" field="providerClass"
                         :validate-trigger="['change', 'blur']" label-col-flex="120px">
              <a-input class="bacClass" :style="{ width: '300px' }" v-model="dataForm.providerClass"/>
            </a-form-item>
            <a-form-item :style="{ width: '355px' }" label="联系人" field="contactPerson" label-col-flex="120px">
              <a-input :style="{ width: '300px' }" class="bacClass" v-model="dataForm.contactPerson"/>
            </a-form-item>

            <a-form-item :style="{ width: '355px' }" label="联系电话1" field="contactPhone" label-col-flex="120px">
              <a-input :style="{ width: '300px' }" class="bacClass" v-model="dataForm.contactPhone"/>
            </a-form-item>

            <a-form-item :style="{ width: '355px' }" label="联系电话2" field="contactPhone2" label-col-flex="120px">
              <a-input :style="{ width: '300px' }" class="bacClass" v-model="dataForm.contactPhone2"/>
            </a-form-item>

            <a-form-item :style="{ width: '355px' }" label="供应商地址" field="providerAddress" label-col-flex="120px">
              <a-input class="bacClass" v-model="dataForm.providerAddress"/>
            </a-form-item>

            <a-form-item :style="{ width: '355px' }" label="开户行" field="bank" label-col-flex="120px">
              <a-input class="bacClass" v-model="dataForm.bank"/>
            </a-form-item>

            <a-form-item :style="{ width: '355px' }" label="是否开票" field="invoicState" label-col-flex="120px">
              <a-input class="bacClass" v-model="dataForm.invoicState"/>
            </a-form-item>

            <a-form-item :style="{ width: '355px' }" label="税率(%)" field="taxRate" label-col-flex="120px"
                         :rules="[{ required: true, message: '税率必填' }]" :validate-trigger="['change', 'blur']">
              <a-input-number v-model="dataForm.taxRate" class="input-demo bacClass" :min="0" :max="1000"/>
            </a-form-item>

            <a-form-item :style="{ width: '355px' }" label="公司法人" field="companyLegalPerson" label-col-flex="120px">
              <a-input class="bacClass" v-model="dataForm.companyLegalPerson"/>
            </a-form-item>

            <a-form-item :style="{ width: '355px' }" label="法人电话" field="legalPersonPhone" label-col-flex="120px">
              <a-input class="bacClass" v-model="dataForm.legalPersonPhone"/>
            </a-form-item>

            <a-form-item :style="{ width: '355px' }" label="统一社会信用代码" field="creditCode" label-col-flex="120px">
              <a-input class="bacClass" v-model="dataForm.creditCode"/>
            </a-form-item>

            <a-form-item :style="{ width: '355px' }" label="开户地址" field="bankAddress" label-col-flex="120px">
              <a-input class="bacClass" v-model="dataForm.bankAddress"/>
            </a-form-item>

            <a-form-item :style="{ width: '355px' }" label="银行账号" field="bankNo" label-col-flex="120px">
              <a-input class="bacClass" v-model="dataForm.bankNo"/>
            </a-form-item>

            <a-form-item :style="{ width: '355px' }" label="收款人" field="collectionPerson" label-col-flex="120px">
              <a-input class="bacClass" v-model="dataForm.collectionPerson"/>
            </a-form-item>

            <a-form-item :style="{ width: '355px' }" label="收款人联系电话" field="collectionPhone"
                         label-col-flex="120px">
              <a-input class="bacClass" v-model="dataForm.collectionPhone"/>
            </a-form-item>

            <a-form-item :style="{ width: '355px' }" label="结算类型" field="settlementType" label-col-flex="120px"
                         key="settlementType">
              <a-select popup-container="html" class="bacClass" v-model="dataForm.settlementType" @focus="focusJs"
                        @search="getJsType" allow-clear allow-search>
                <a-option v-for="(item, index) in pageData.jsTypeList" :key="item.settlementName">{{
                    item.settlementName
                  }}
                </a-option>
              </a-select>
            </a-form-item>

            <a-form-item :style="{ width: '355px' }" label="结算币种" field="settlementMoneyType" label-col-flex="120px"
                         key="settlementMoneyType">
              <a-select popup-container="html" class="bacClass" v-model="dataForm.settlementMoneyType" @focus="focusBl"
                        @search="focusBl" allow-clear allow-search>
                <a-option v-for="(item, index) in hbType" :key="index">{{ item.detailName }}
                </a-option>
              </a-select>
            </a-form-item>
            <a-form-item :style="{ width: '355px' }" label="对接人" field="contactPerson2" label-col-flex="120px">
              <a-input class="bacClass" v-model="dataForm.contactPerson2"/>
            </a-form-item>

            <a-form-item :style="{ width: '355px' }" label="经营范围" field="operateRange" label-col-flex="120px">
              <a-input class="bacClass" v-model="dataForm.operateRange"/>
            </a-form-item>
            <a-form-item :style="{ width: '355px' }" label-col-flex="120px" label="物料大类">
              <a-select popup-container="html" multiple class="bacClass" :loading="loadings" @click="bigClassClick"
                        @change="focusSelsss" v-model="dataForm.bigClassName" :filter-option="false" allow-search
                        allow-clear>
                <a-option v-for="item in bigClassList">{{ item.bigClassName }}</a-option>
              </a-select>
            </a-form-item>
            <a-form-item :style="{ width: '355px' }" label-col-flex="120px" label="物料中类">
              <a-select popup-container="html" multiple class="bacClass" :disabled="!dataForm.bigClassName"
                        :loading="loadings" @click="middleClassClick" @change="focusSelsss2"
                        v-model="dataForm.middleClassName"
                        :filter-option="false" allow-search allow-clear>
                <a-option v-for="item in middleClassList">{{ item.middleClassName }}</a-option>
              </a-select>
            </a-form-item>
            <a-form-item :style="{ width: '355px' }" label-col-flex="120px" label="物料小类">
              <a-select popup-container="html" multiple class="bacClass" :disabled="!dataForm.middleClassName"
                        allow-clear
                        allow-search v-model="dataForm.subClassName" :style="{ width: '320px' }" @click="subClassClick">
                <a-option v-for="item in subClassList">{{ item.subClassName }}</a-option>
              </a-select>
            </a-form-item>
            <a-form-item :style="{ width: '1493px' }" label="备注" field="remark" label-col-flex="120px">
              <a-textarea class="bacClass" v-model="dataForm.remark" :max-length="400" allow-clear show-word-limit/>
            </a-form-item>
            <a-upload :file-list="fileList" :custom-request="customRequest" :on-before-remove="changeFilrList"/>
          </a-form>
        </el-scrollbar>
      </div>
    </a-drawer>
  </pageTabelLayout>
</template>

<script lang="ts">
import {post, get} from '@/api/http'
import {
  useTable,
  useRowKey,
  useTableColumn,
  usePagination,
  useRowSelection,
} from '@/hooks/table'
import emitter from '@/hooks/useEventBus'
import {ref, reactive, onMounted, toRefs} from 'vue'
import Toolbar from '@/components/Toolbar.vue'
import {Form, Message, Modal} from '@arco-design/web-vue'
import {FormInstance} from '@arco-design/web-vue/es/form'
import {String} from 'lodash'
import {baseURL} from '@/api/axios.config'
import axios from 'axios'
import usePermission from '@/store/modules/permission'

import {localeText} from '@/api/aggridZw'
import {pagingList} from '@/api/paging'
import {simplifyMessages} from '@/api/messageSimplification'
import filedownload from 'js-file-download'
import {saveOrUpdateGridState as saveOrUpdateGridState01} from '@/hooks/useGridState'
import buttionRender from "@/components/aggridCellRenDerer/buttionRender.vue";

interface SettlementType {
  id: any
  providerCode: any
  providerName: any
  providerClass: any
  contactPerson: any
  contactPhone: any
  providerAddress: any
  creditCode: any
  invoicState: any
  taxRate: any
  companyLegalPerson: any
  legalPersonPhone: any
  bank: any
  bankAddress: any
  settlementTypeId: any
  settlementType: any
  settlementMoneyType: any
  remark: any
  deleteState: any
  createName: any
  createTime: any
  updateName: any
  updateTime: any
  bankNo: any
  collectionPhone: any
  collectionPerson: any
  bigClassName: any
  middleClassName: any
  subClassName: any
  bigClassId: any
  contactPhone2: any
  operateRange: any
  contactPerson2: any
  providerType: any
}

export default {
  name: 'Supplier',
  setup() {
    const pageData = reactive<{
      nameList: any
      showAdd: boolean
      sideTitle: string
      dropDownData: any
      pageLoading: boolean
      rHeight: any
      btnList: any[]
      isEdit: boolean
      jsTypeList: any[]
      nameLists1: []
      providerTypeList: any[]
    }>({
      nameList: [],
      showAdd: false,
      sideTitle: '新增产品基础资料',
      dropDownData: '',
      pageLoading: false,
      rHeight: '',
      btnList: [],
      isEdit: false,
      jsTypeList: [],
      nameLists1: [],
      providerTypeList: [],
    })
    //设置权限
    // ['查询', '新增', '删除', '导出', '导入']
    const permissionStore = usePermission()

    if (permissionStore.hasPermisson('gyszl.cx')) {
      pageData.btnList.push('查询')
    }
    if (permissionStore.hasPermisson('gyszl.xz')) {
      pageData.btnList.push('新增')
    }
    if (permissionStore.hasPermisson('gyszl.sc')) {
      pageData.btnList.push('删除')
    }
    if (permissionStore.hasPermisson('gyszl.xg')) {
      pageData.isEdit = true
    }
    const table1Ref = ref<any>(null)
    const tableColumns = [
      {
        field: '',
        headerCheckboxSelection: true,
        checkboxSelection: true,
        width: 60,
        showDisabledCheckboxes: false,
        pinned: 'left',
      },
      {
        headerName: '供应商编号',
        field: 'providerCode',
        width: 150,
      },
      {
        headerName: '供应商名称',
        field: 'providerName',
        width: 150,
      },
      {
        headerName: '供应商地址',
        field: 'providerAddress',
        width: 150,
      },
      {
        headerName: '物料大类',
        field: 'bigClassName',
        width: 150,
      },
      {
        headerName: '物料中类',
        field: 'middleClassName',
        width: 150,
      },
      {
        headerName: '物料小类',
        field: 'subClassName',
        width: 150,
      },
      {
        headerName: '联系人',
        field: 'contactPerson',
        width: 150,
      },
      {
        headerName: '联系电话1',
        field: 'contactPhone',
        width: 150,
      },
      {
        headerName: '联系电话2',
        field: 'contactPhone2',
        width: 150,
      },
      {
        headerName: '对接人',
        field: 'contactPerson2',
        width: 150,
      },
      {
        headerName: '经营范围',
        field: 'operateRange',
        width: 150,
      },
      {
        headerName: '税率',
        field: 'taxRate',
        width: 150,
      },
      {
        headerName: '统一社会信用代码',
        field: 'creditCode',
        width: 150,
      },
      {
        headerName: '开户行',
        field: 'bank',
        width: 150,
      },
      {
        headerName: '开户地址',
        field: 'bankAddress',
        width: 150,
      },
      {
        headerName: '银行账号',
        field: 'bankNo',
        width: 150,
      },
      {
        headerName: '收款人',
        field: 'collectionPerson',
        width: 150,
      },
      {
        headerName: '收款人联系电话',
        field: 'collectionPhone',
        width: 150,
      },
      {
        headerName: '结算方式',
        key: 'settlementType',
        dataIndex: 'settlementType',
        width: 150,
      },
      {
        headerName: '备注',
        field: 'remark',
        width: 150,
      },
      {
        headerName: '创建人',
        field: 'createName',
        width: 150,
      },
      {
        headerName: '创建时间',
        field: 'createTime',
        width: 200,
      },
      {
        headerName: '最后修改人',
        field: 'updateName',
        width: 150,
      },
      {
        headerName: '最后修改时间',
        field: 'updateTime',
        width: 200,
      },
      {
        headerName: '操作',
        field: 'action',
        slotName: 'action',
        width: 150,
        pinned: 'right',
        cellRenderer: buttionRender,
        cellRendererParams: {
          buttonList: [
            {
              type: 'success',
              text: '修改',
              show: pageData.isEdit,
              typeName: 'el-button',
              Callback: (data: any) => {
                getProviderTypeList()
                editHandler(data)
              },
            },
          ],
          eltagSize: 0,
        },
      },
    ]
    let configTable1 = {
      url: 'purchase/Provider/getPage', //接口路径
      queryData: {
        deleteState: 0,
        providerName: pageData.dropDownData,
      },
      paginationShow: true, //分页是否显示
      invokeiIterface: true, //是否调用接
      rowMultiSelectWithClick: true, //点击行是否多选
      column: tableColumns,
      fileName: 'Supplier01'
    }

    const total = ref(0)
    const page = ref(1)
    const size = ref(10)

    function PageSizes(val: any) {
      page.value = val
      doRefresh()
    }

    function change1s(val: any) {
      size.value = val
      doRefresh()
    }

    function doRefresh() {
      table1Ref.value.setQuery({
        deleteState: 0,
        providerName: pageData.dropDownData,
      })
      // pageData.pageLoading = true
      // post({
      //   url: 'purchase/Provider/getPage',
      //   data: {
      //     page: page.value,
      //     size: size.value,
      //     deleteState: 0,
      //     providerName: pageData.dropDownData,
      //   },
      // })
      //     .then(({data, code}: any) => {
      //       if (code === 200) {
      //         table.handleSuccess(data.list)
      //         // pagination.setTotalSize(data.total);
      //         gridOption.value.setRowData(data.list)
      //         total.value = data.total
      //       }
      //     })
      //     .catch(console.log)
      //     .finally(() => {
      //       pageData.pageLoading = false
      //     })
    }

    const {selectedRowKeys, onSelectionChange} = useRowSelection()
    const pagination = usePagination(doRefresh)
    const table = useTable()
    const rowKey = useRowKey('id')
    //下拉框得到焦点
    const focusSel = () => {
      selCxAll({providerName: ''})
    }
    //下拉数据
    const options = ref<any>(pageData.nameList)
    const loading = ref(false)
    const handleSearch = (value: any) => {
      if (value) {
        const ob = {providerName: value}
        loading.value = true
        window.setTimeout(() => {
          selCxAll(ob)
          options.value = pageData.nameList
          loading.value = false
        }, 200)
      } else {
        options.value = []
      }
    }

    //下拉框查询
    function selCxAll(val: any) {
      post({
        url: 'purchase/Provider/getFieldValue',
        data: val,
      }).then(({data, code}: any) => {
        if (code === 200) {
          console.log(data)
          // (data as string[]).splice(0, 0, "全部");
          pageData.nameList = data
        } else {
          Message.error({
            content: '查询失败！',
            duration: 5000,
          })
        }
      })
    }

    //下拉框得到焦点
    const focusSels1 = () => {
      selCxAlls1({subClassName: ''})
    }
    //下拉数据
    const optionss1 = ref<any>(pageData.nameLists1)
    const loadings1 = ref(false)
    const handleSearchs1 = (value: any) => {
      if (value) {
        const ob = {subClassName: value}
        loadings1.value = true
        selCxAlls1(ob)
        optionss1.value = pageData.nameLists1
        loadings1.value = false
      } else {
        optionss1.value = []
      }
    }

    //下拉框查询
    function selCxAlls1(val: any) {
      post({
        url: 'purchase/MaterialSubClass/getFieldValue',
        data: val,
      }).then(({data, code}: any) => {
        if (code === 200) {
          console.log(data)
          // (data as string[]).splice(0, 0, "全部");
          pageData.nameLists1 = data
        } else {
          Message.error({
            content: '查询失败！',
            duration: 5000,
          })
        }
      })
    }

    onMounted(() => {
      // 切换tap到本页面执行的方法
      emitter.on('Supplier', () => {
        doRefresh()
      })
      pageData.rHeight = document.getElementsByClassName('main-base-style')[0]?.clientHeight
      //表格的高
      if (pageData.rHeight !== undefined) {
        pageData.rHeight = pageData.rHeight - 200
      }
      window.addEventListener('resize', () => {
        pageData.rHeight = document.getElementsByClassName('main-base-style')[0]?.clientHeight

        //表格的高
        if (pageData.rHeight !== undefined) {
          pageData.rHeight = pageData.rHeight - 200
        }
      })
    })
    //查询
    let hbType: any = ref()
    const selectHandler = () => {
      page.value = 1
      doRefresh()
    }
    const queryData = reactive({
      clothType: '',
    })
    const getProviderTypeList = async () => {
      try {
        const res = await post({
          url: 'dict/dictTypeDetail/getList',
          data: {codeType: 49},
        })
        if (res.code == 200) {
          pageData.providerTypeList = res.data.map((item: any) => {
            return {
              detailName: item.detailName,
              detailCode: item.detailCode,
            }
          })
        } else {
          Message.error({
            content: res.message,
          })
        }
      } catch (error) {
        console.log(error)
      }
    }
    const provideTypeChange = async (e: any) => {
      try {
        const providerTypeCode = pageData.providerTypeList.find(
            (item: any) => item.detailName === e
        )['detailCode']
        const res = await post({
          url: '/purchase/Provider/getCodeGenerate',
          data: {providerTypeCode},
        })
        if (res.code == 200) {
          dataForm.providerCode = res.data
        }
      } catch (error) {
        console.log(error)
      }
    }
    const addHandler = () => {
      fileAddress.value = []
      fileList.value = []
      getProviderTypeList()
      //清空数据
      for (const key in dataForm) {
        if (key == 'id') {
          dataForm.id = null
        } else {
          dataForm[key] = ''
        }
      }
      dataForm.settlementType = '人名币'
      pageData.showAdd = true
      pageData.sideTitle = '新增供应商资料'
    }

    const dataForm = reactive<SettlementType>({
      id: '',
      providerCode: '',
      providerName: '',
      providerClass: '',
      contactPerson: '',
      contactPhone: '',
      providerAddress: '',
      creditCode: '',
      invoicState: '',
      taxRate: '',
      companyLegalPerson: '',
      legalPersonPhone: '',
      bank: '',
      bankAddress: '',
      settlementTypeId: '',
      settlementType: '',
      settlementMoneyType: '',
      remark: '',
      deleteState: '',
      createName: '',
      createTime: '',
      updateName: '',
      updateTime: '',
      bankNo: '',
      collectionPhone: '',
      collectionPerson: '',
      bigClassName: '',
      middleClassName: '',
      subClassName: '',
      bigClassId: null,
      contactPerson2: '',
      operateRange: '',
      contactPhone2: '',
      providerType: '',
    })

    // 表格准备事件
    const gridOption = ref()
    const colState = ref()
    const gridReady = (params: any) => {
      gridOption.value = params.api
      colState.value = params.columnApi
    }
    const ifOpen = () => {
      if (dataForm.bigClassName == '' || dataForm.bigClassName.length == 0) {
        dataForm.bigClassName = ''
      } else {
        dataForm.bigClassName = dataForm.bigClassName.join(',')
      }
      if (dataForm.middleClassName == '' || dataForm.middleClassName.length == 0) {
        dataForm.middleClassName = ''
      } else {
        dataForm.middleClassName = dataForm.middleClassName.join(',')
      }
      if (dataForm.subClassName == '' || dataForm.subClassName.length == 0) {
        dataForm.subClassName = ''
      } else {
        dataForm.subClassName = dataForm.subClassName.join(',')
      }
    }
    const formRef = ref<FormInstance>()
    const sideOk = () => {
      formRef.value?.validate().then((err) => {
        if (!err) {
          ifOpen()

          if (pageData.sideTitle === '新增供应商资料') {
            pageData.pageLoading = true
            dataForm.id = null
            post({
              url: 'purchase/Provider/insert',
              data: [{
                ...dataForm,
                fileAddress: fileAddress.value.join(',')
              }],
            })
                .then((res: any) => {
                  if (res.code === 200) {
                    formRef.value?.resetFields()
                    pageData.showAdd = false
                    pageData.dropDownData = ''
                    doRefresh()
                    Message.success({
                      content: '新增成功',
                      duration: 5000,
                    })
                  } else {
                    ifOpen()
                    Message.error({
                      content: res.message,
                      duration: 5000,
                    })
                  }
                })
                .finally(() => {
                  pageData.pageLoading = false
                })
          } else {
            post({
              url: 'purchase/Provider/update',
              data: [{
                ...dataForm,
                fileAddress: fileAddress.value.join(',')
              }],
            }).then((res: any) => {
              if (res.code === 200) {
                formRef.value?.resetFields()
                pageData.showAdd = false
                doRefresh()
                //清空数据
                for (const key in dataForm) {
                  if (key == 'id') {
                    dataForm.id = null
                  } else {
                    dataForm[key] = ''
                  }
                }
                Message.success({
                  content: '修改成功',
                  duration: 5000,
                })
              } else {
                ifOpen()
                Message.error({
                  content: simplifyMessages(res.message),
                  duration: 5000,
                })
              }
            })
          }
        }
      })
    }
    const deleteHandler = () => {
      if (table1Ref.value.getSelectedRows().length === 0) {
        Message.error('请先勾选')
        return
      }
      Modal.confirm({
        title: '系统提示',
        content: '确认删除选中的数据?',

        onOk() {
          post({
            url: 'purchase/Provider/delete',
            // data: selectedRowKeys.value
            data: table1Ref.value.getSelectedRows().map((o: any) => {
              return o.id
            }),
          }).then(({code, data, message}: any) => {
            if (code === 200) {
              page.value = 1
              doRefresh()
              Message.success({
                content: '删除成功',
                duration: 5000,
              })
            } else {
              Message.success({
                content: simplifyMessages(message),
                duration: 5000,
              })
            }
          })
        },
      })
    }
    const editHandler = (record: any) => {
      fileList.value = []
      if (record.fileAddress != null && record.fileAddress != undefined && record.fileAddress != '') {
        fileAddress.value = record.fileAddress.split(',')
        fileAddress.value.forEach((res: any, index: any) => {
          fileList.value.push({
            name: res,
            uid: index,
            url: `${baseURL}/minio/file/download/zzy/${res}`
          })
        })
      } else {
        fileList.value = []
      }

      dataForm.id = Number(record.id)
      dataForm.providerType = record.providerType
      dataForm.providerCode = record.providerCode
      dataForm.providerName = record.providerName
      dataForm.providerClass = record.providerClass
      dataForm.contactPerson = record.contactPerson
      dataForm.contactPhone = record.contactPhone
      dataForm.providerAddress = record.providerAddress
      dataForm.creditCode = record.creditCode
      dataForm.invoicState = record.invoicState
      dataForm.taxRate = record.taxRate
      dataForm.companyLegalPerson = record.companyLegalPerson
      dataForm.legalPersonPhone = record.legalPersonPhone
      dataForm.bank = record.bank
      dataForm.bankAddress = record.bankAddress
      dataForm.settlementType = record.settlementType
      dataForm.settlementMoneyType = record.settlementMoneyType
      dataForm.remark = record.remark
      dataForm.bankNo = record.bankNo
      dataForm.collectionPerson = record.collectionPerson
      dataForm.collectionPhone = record.collectionPhone
      if (record.bigClassName == '') {
        dataForm.bigClassName = ''
      } else {
        dataForm.bigClassName = record.bigClassName.split(',')
      }
      if (record.subClassName == '') {
        dataForm.subClassName = ''
      } else {
        dataForm.subClassName = record.subClassName.split(',')
      }
      if (record.middleClassName == '') {
        dataForm.middleClassName = ''
      } else {
        dataForm.middleClassName = record.middleClassName.split(',')
      }
      pageData.sideTitle = '修改供应商资料'
      pageData.showAdd = true
    }
    //判断是否填写了中文
    const isChiese = (value: string, cb: Function) => {
      return new Promise<void>((resolve) => {
        if (window.encodeURI(value).indexOf('%') !== -1) {
          cb('填写的值不能包含中文！')
        }
        resolve()
      })
    }
    //input离开焦点 将小写转大写
    const inputBlur = () => {
      dataForm.providerCode = dataForm.providerCode.toUpperCase()
    }
    //导出
    const exports = () => {
      // if (selectedRowKeys.value.length === 0) {
      //     Message.error('请先勾选')
      //     return
      // }
      if (gridOption.value.getSelectedRows() === 0) {
        Message.error('请先勾选')
        return
      } else {
        //将表头拼接出来
        let head =
            '<th>类型编号</th><th>类型名称</th><th>备注</th><th>创建人</th><th>创建时间</th><th>最后修改人</th><th>最后修改时间</th>'
        //拿到当前表格数据与勾选的行做筛选

        let nowRow = table.dataList.filter(function (o) {
          return selectedRowKeys.value.indexOf(o['id']) !== -1
        })
        let body = ''
        nowRow.forEach(function (o) {
          body += '<tr><td>' + o['productTypeCode'] + '</td>'
          body += '<td>' + o['productTypeName'] + '</td>'
          body += '<td>' + o['remark'] + '</td>'
          body += '<td>' + o['createName'] + '</td>'
          body += '<td>' + o['createTime'] + '</td>'
          body += '<td>' + o['updateName'] + '</td>'
          body += '<td>' + o['updateTime'] + '</td>'
          body += '</tr>'
        })
        tableToXlsx(head, '产品类型', body)
        console.log(table)
      }
    }

    function tableToXlsx(head: any, filename: any, body: any) {
      const uri = 'data:application/vnd.ms-excel;base64,',
          template = `<html>
            <head><meta charset="UTF-8"></head>
            <body><table border="1"><tr>${head}</tr>${body}</table></body>
        </html>`

      const a = document.createElement('a')
      a.href = uri + window.btoa(unescape(encodeURIComponent(template)))
      a.download = filename
      a.click()
      document.removeChild(a)
    }

    //模板下载
    const downloadHandler = () => {
      get({
        url: '/purchase/Provider/uploadModel',
        responseType: 'blob',
      }).then((res: any) => {
        filedownload(res, '供应商资料.xlsx')
      })
    }
    //导入
    const importHandler = () => {
      const inputEle: HTMLInputElement = document.createElement('input')
      inputEle.type = 'file'
      inputEle.id = 'fileUploadExcel'
      inputEle.accept =
          'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel'
      inputEle.addEventListener('change', (e) => {
        const formData = new FormData()
        if (inputEle.files !== null) {
          formData.append('file', inputEle.files[0] || '')
        } else {
          Message.warning('未选择文件！')
          return
        }
        pageData.pageLoading = true
        axios
            .post(baseURL + '/purchase/Provider/importModelData', formData, {
              headers: {
                'Content-Type': 'multipart/form-data',
                token: sessionStorage.getItem('USER-TOKEN-KEY'),
              },
            })
            .then((result) => {
              if (result.data['code'] === 200) {
                Message.success('导入成功')
                page.value = 1
                doRefresh()
              } else {
                Message.error(result.data.message)
              }
            })
            .finally(() => {
              pageData.pageLoading = false
              doRefresh()
            })
      })
      inputEle.click()
    }
    const focusJs = () => {
      getJsType({settlementType: ''})
    }
    const focusBl = () => {
      post({
        url: 'dict/dictTypeDetail/getListByCodeType?codeType=14',
      }).then((res: any) => {
        if (res.code == 200) {
          hbType.value = res.data
        }
      })
    }
    //结算类型下拉框
    const getJsType = (ob: any) => {
      if (typeof ob == 'string') {
        ob = {settlementType: ob}
      }
      post({
        url: 'purchase/SettlementType/getList',
        data: ob,
      }).then(({code, data}: any) => {
        if (code === 200) {
          pageData.jsTypeList = data
        } else {
          Message.success({
            content: '查询结算类型下拉框失败',
            duration: 5000,
          })
        }
      })
    }

    const headerShow = ref<boolean>(true)
    const handleChange = (_data: any) => {
      table.handleSuccess(_data)
    }
    const defaultColDef = {
      sortable: true,
      resizable: true,
      filter: true,
      // flex: 1
    }
    let dataListXl = ref<any[]>([])
    // const focusSelsss = (val: any) => {
    //     post({
    //         url: 'purchase/MaterialSubClass/getList',
    //         data: {
    //             bigClassName: val
    //         }
    //     }).then((res: any) => {
    //         if (res.code == 200) {
    //             dataListXl.value = res.data
    //         } else {
    //             Message.error('获取失败')
    //         }
    //     })
    // }
    // const isDatas = (val: any) => {
    // post({
    //     url: 'purchase/MaterialSpec/getList',
    //     data: {
    //         providerClass: val
    //     }
    // }).then((res: any) => {
    //     if (res.code == 200) {
    //     } else {
    //         Message.error('获取失败')
    //     }
    // })

    // }

    const localeText1: any = ref(localeText)
    const huiche = () => {
      selectHandler()
    }
    const pagingList1: any = ref(pagingList)
    const isChiese1 = (value: string, cb: Function) => {
      return new Promise<void>((resolve) => {
        var reg = /^[\u4E00-\u9FA5]+$/
        if (!reg.test(value)) {
          cb('请填写中文！')
        }
        resolve()
      })
    }
    const bigClassList: any = ref([])

    const bigClassClick = () => {
      post({
        url: 'purchase/MaterialBigClass/getList',
        data: {},
      }).then(({data}) => {
        bigClassList.value = data
      })
    }
    const bigClassIdList: any = ref([])
    const focusSelsss = (val: any) => {
      bigClassIdList.value = []
      bigClassList.value.forEach((res: any) => {
        for (var i = 0; i < val.length; i++) {
          if (res.bigClassName == val[i]) {
            bigClassIdList.value.push(res.id)
          }
        }
      })
      dataForm.subClassName = ''
      dataForm.middleClassName = ''
    }

    const middleClassList: any = ref([])
    const middleClassClick = () => {
      post({
        url: '/purchase/MaterialMiddleClass/getMultipleCascadeList',
        data: bigClassIdList.value,
      }).then(({data}) => {
        middleClassList.value = data
      })
    }
    const middleClassIdList: any = ref([])
    const focusSelsss2 = (val: any) => {
      middleClassIdList.value = []
      middleClassList.value.forEach((res: any) => {
        for (var i = 0; i < val.length; i++) {
          if (res.middleClassName == val[i]) {
            middleClassIdList.value.push(res.id)
          }
        }
      })
      dataForm.subClassName = ''
    }

    const subClassList: any = ref([])
    const subClassClick = () => {
      post({
        url: '/purchase/MaterialSubClass/getMultipleCascadeList',
        data: middleClassIdList.value,
      }).then(({data}) => {
        subClassList.value = data
      })
    }
    const loadings = ref(false)

    const fileList: any = ref([])

    const fileAddress: any = ref([])

    const customRequest: any = (option: any) => {
      const {onProgress, onError, onSuccess, fileItem, name} = option
      const formData = new FormData();
      formData.append('file', fileItem.file);
      console.log(name)
      post({
        url: 'minio/file/upload',
        data: formData,
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }).then((res: any) => {
        if (res.code == 200) {
          fileAddress.value.push(res.data.data)
          fileList.value = fileAddress.value.map((res: any, index: any) => {
            return {
              name: res,
              uid: index,
              url: `${baseURL}/minio/file/download/zzy/${res}`
            }
          })
          onSuccess(res.data.data);
        } else {
          Message.error(res.message)
          onError(res.message);
        }
      })
    }

    const changeFilrList: any = (e: any) => {
      fileList.value = fileList.value.filter((res: any) => {
        return res.name != e.name
      })
      fileAddress.value = fileAddress.value.filter((res: any) => {
        return res != e.name
      })
      console.log(fileList.value)
      console.log(fileAddress.value)
    }
    return {
      changeFilrList,
      fileAddress,
      customRequest,
      fileList,
      ifOpen,
      bigClassIdList,
      middleClassIdList,
      subClassList,
      middleClassList,
      bigClassList,
      loadings,
      bigClassClick,
      focusSelsss,
      middleClassClick,
      focusSelsss2,
      subClassClick,
      colState,
      permissionStore,
      pagingList1,
      huiche,
      localeText1,
      handleSearchs1,
      // isDatas,
      defaultColDef,
      gridOption,
      gridReady,
      total,
      headerShow,
      hbType,
      deleteHandler,
      sideOk,
      formRef,
      dataForm,
      addHandler,
      selectedRowKeys,
      pagination,
      tableColumns,
      table,
      rowKey,
      pageData,
      queryData,
      editHandler,
      selectHandler,
      inputBlur,
      isChiese,
      exports,
      options,
      loading,
      handleSearch,
      focusSel,
      downloadHandler,
      importHandler,
      getJsType,
      focusJs,
      focusBl,
      PageSizes,
      change1s,
      page,
      size,
      handleChange,
      focusSels1,
      isChiese1,
      provideTypeChange,
      getProviderTypeList,
      table1Ref,
      configTable1
    }
  },
  components: {Toolbar, },
}
</script>
<style scoped lang="less">
:deep(.ag-cell) {
  border-right: 1px solid #dde2eb;
}

:deep(.ag-header-cell) {
  border-right: 1px solid #dde2eb;
}

:deep(.ag-cell-value) {
  user-select: initial;
  -moz-user-select: text;
  -ms-user-select: text;
  -webkit-user-select: text;
}
</style>
